package com.wm.blog_admin.event;

import com.alibaba.fastjson.JSONObject;
import com.wm.blog_admin.domain.WebScoketMsg;
import com.wm.blog_common.util.StringUtil;
import com.wm.blog_config.config.WebSocketServerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Optional;

/**
 * @author wm_yu  监听图标事件变化
 * @date 2020-4-29 11:23
 */
@Component
@Slf4j
public class WebSocketEventListener implements ApplicationListener<MessageEvent> {

    @Autowired
    private WebSocketServerConfig webSocketServerConfig;

    @Override
    public void onApplicationEvent(MessageEvent event) {
        WebScoketMsg scoketMsg = Optional.ofNullable(event.getWebScoketMsg()).orElse(new WebScoketMsg());
        if(ObjectUtils.isEmpty(scoketMsg.getMsg())){
            log.info("推送消息为空....");
            return;
        }
        String msg = JSONObject.toJSONString(scoketMsg.getMsg());
        log.info("需要推送的消息为:[{}]",msg);
        if(StringUtil.isEmpty(scoketMsg.getSessionId())){
            webSocketServerConfig.sendMessageToAll(msg);
            //消息群发
        }else {
            //给某个session单独推送消息
            webSocketServerConfig.sendMessage(scoketMsg.getSessionId(),msg);
        }

    }
}
